package com.yc.backstage.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yc.backstage.common.listener.UserImportDtoListener;
import com.yc.backstage.entity.SysUser;
import com.yc.backstage.entity.dto.UserImExDto;
import com.yc.backstage.mapper.SysUserMapper;
import com.yc.backstage.service.ExcelService;
import com.yc.backstage.service.SysUserService;
import com.yc.common.constant.Constants;
import com.yc.common.utils.EasyExcelUtils;
import com.yc.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Classname ExcelServiceImpl
 * @Description 导入导出
 * @Version 1.0.0
 * @Date 2022/9/1 10:49
 * @Created by Mikechen
 */
@Service
public class ExcelServiceImpl implements ExcelService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisUtils redisUtil;
    /**
     * 导入用户数据
     */
    @Override
    public void importData(MultipartFile file) throws IOException {
        //将数据库中的数据存到redis做唯一性校验
        List<SysUser> users = sysUserMapper.selectList(new QueryWrapper<>());
        //存放用户数据集合
        Map<String,Object> map=new HashMap<>();
        users.stream().forEach(user->{
            //用户名和手机号确定一名用户
            String key = user.getUserName() + "-" + user.getPhonenumber();
            map.put(key,1);
        });
        //创建监听器
        UserImportDtoListener userImportDtoListener = new UserImportDtoListener(map);
        //使用流来读取
        EasyExcelUtils.asyncReadModel(file.getInputStream(),userImportDtoListener,UserImExDto.class);
    }

    /**
     * 导出用户数据
     */
    @Override
    public String exportUser(HttpServletResponse response) throws IOException {
        List<UserImExDto> data=sysUserService.getUserAll();
        String fileName=new String("用户表.xlsx".getBytes(), StandardCharsets.UTF_8)+new SimpleDateFormat().format(new Date());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition","attachment;fileName="+fileName);
        //导出到Excel
        EasyExcelUtils.write(response.getOutputStream(),UserImExDto.class,data,"用户数据");
        return fileName;
    }
}
